package com.zky.dao;

import cn.hutool.json.JSONUtil;
import com.zky.domain.po.Disease;
import com.zky.utils.RedisUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@RequiredArgsConstructor
public class DiseaseDao {

    private final StringRedisTemplate stringRedisTemplate;
    private final RedisUtil redisUtil;

    private static final String KEY = "disease";

    public List<Disease> getAll() {
        return redisUtil.getListForSet(KEY, Disease.class);
    }

    public void add(Disease disease) {
        redisUtil.addForSet(KEY, disease);
    }

    public void addBatch(List<Disease> list) {
        redisUtil.addForSet(KEY, JSONUtil.toJsonStr(list));
    }

    public void deleteById(Long id) {
        List<Disease> all = new ArrayList<>(getAll());
        all.removeIf(item -> item.getId().equals(id));
        stringRedisTemplate.delete(KEY);
        addBatch(all);
    }

    public void update(Disease disease) {
        List<Disease> all = new ArrayList<>(getAll());
        for (int i = 0; i < all.size(); i++) {
            if (all.get(i).getId().equals(disease.getId())) {
                all.set(i, disease);
                break;
            }
        }
        stringRedisTemplate.delete(KEY);
        addBatch(all);
    }
}



